<!--
 * @Author: early-autumn
 * @Date: 2020-05-20 15:44:10
 * @LastEditors: early-autumn
 * @LastEditTime: 2020-06-17 15:36:52
-->
<template>
  <el-dialog
    :title="form.id ? '修改预约' : '新建预约'"
    :visible="value"
    width="1080px"
    @close="handleClose"
  >
    <template v-if="value">
      <default-patient
        v-if="defaultPatient"
        :patient="defaultPatient"
      ></default-patient>
      <user-matcher v-else @change="handleClinicPersonId"></user-matcher>
    </template>

    <el-row :gutter="20">
      <el-col :span="8">
        <seeing-project
          v-model="form.reservationProject"
          :types="types"
          :show="value"
        ></seeing-project>
      </el-col>
      <el-col :span="8">
        <appointment-time
          v-if="value"
          ref="appointmentTime"
          :height="500"
          :header="null"
          :resources="resources"
          :events="events"
          @event-change="handleEventChange"
          @add="handleEventChange"
        ></appointment-time>
      </el-col>
      <el-col :span="8">
        <basic-information
          :doctor-options="doctorWork"
          :date.sync="form.reservationDate"
          :duration.sync="continueTime"
          :doctor-id.sync="form.doctorId"
          :doctor-name.sync="form.doctorName"
          :remarks.sync="form.remarks"
          :tc-id.sync="form.tcId"
          :tc-name.sync="form.tcName"
          @update:date="handleDate"
          @update:duration="handleUpdateDuration"
        ></basic-information>
      </el-col>
    </el-row>

    <span slot="footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        确定
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import { mapState } from 'vuex'
import dayjs from 'dayjs'
import { listStaff } from '@/api/services/common'
import { listPlan } from '@/api/services/plan'
import {
  addAppointment,
  listAppointment,
  updateAppointment,
} from '@/api/services/appointment'
import { appointmentColorEnum } from '@/utils/enums'

import AppointmentTime from '@/components/yiya/AppointmentTime'
import UserMatcher from './UserMatcher'
import DefaultPatient from './DefaultPatient'
import SeeingProject from './SeeingProject'
import BasicInformation from './BasicInformation'

const FORM_DATA = {
  id: undefined,
  clinicPersonId: undefined,
  clinicPersonName: undefined,
  doctorId: undefined,
  doctorName: undefined,
  tcId: undefined,
  tcName: undefined,
  reservationProject: '',
  reservationDate: dayjs().format('YYYY-MM-DD'),
  startReservationTime: undefined,
  endReservationTime: undefined,
  remarks: undefined,
}

export default {
  name: 'AppointmentPanel',
  components: {
    AppointmentTime,
    DefaultPatient,
    UserMatcher,
    SeeingProject,
    BasicInformation,
  },
  model: {
    prop: 'value',
    event: 'close',
  },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    defaultData: {
      type: Object,
      default: undefined,
    },
    defaultPatient: {
      type: Object,
      default: undefined,
      required: false,
    },
    types: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      loading: false,
      //
      form: {},
      // 医生列表
      doctorList: [],
      // 休息集合
      restMap: {},
      // 今天日期
      today: dayjs().format('YYYY-MM-DD'),
      // 预约列表
      appointmentList: [],
      // 持续时间
      continueTime: 15,
    }
  },
  computed: {
    ...mapState({
      clinicName: (state) => state.clinic.clinicName,
      clinicId: (state) => state.clinic.clinicId,
      userName: (state) => state.user.name,
    }),
    doctorWork() {
      const { reservationDate } = this.form
      return reservationDate > this.today
        ? this.doctorList
        : this.doctorList.filter((doctor) => !this.restMap[doctor.userId])
    },
    resources() {
      const { reservationDate } = this.form
      if (!reservationDate) {
        return []
      }
      const weeks = ['日', '一', '二', '三', '四', '五', '六']
      const index = dayjs(reservationDate).$W
      return [
        {
          id: reservationDate,
          title: `${reservationDate} 星期${weeks[index]}`,
          date: reservationDate,
        },
      ]
    },
    events() {
      const {
        clinicPersonId,
        doctorId,
        reservationDate,
        startReservationTime,
        endReservationTime,
      } = this.form
      if (!reservationDate) {
        return []
      }
      return [
        {
          id: 'new',
          title: this.form.id ? '修改预约' : '新建预约',
          resourceId: reservationDate,
          start: dayjs(startReservationTime).format('YYYY-MM-DD HH:mm'),
          end: dayjs(endReservationTime).format('YYYY-MM-DD HH:mm'),
          editable: true,
        },
        ...this.appointmentList
          .filter(
            (appointment) =>
              appointment.clinicPersonId != clinicPersonId &&
              (doctorId ? appointment.doctorId == doctorId : true)
          )
          .map((appointment) => ({
            id: appointment.id,
            title: appointment.clinicPersonName,
            resourceId: appointment.reservationDate,
            start: appointment.startReservationTime,
            end: appointment.endReservationTime,
            editable: false,
            backgroundColor:
              appointmentColorEnum[appointment.appointmentStatus],
          })),
      ]
    },
  },
  watch: {
    value(val) {
      if (val) {
        this.init()
      }
    },
  },
  mounted() {
    this.getListStaff()
  },
  methods: {
    async init() {
      this.loading = false
      let formData = {}
      if (this.defaultData) {
        const { startReservationTime, endReservationTime } = this.defaultData
        const [start, end] = [
          dayjs(startReservationTime),
          dayjs(endReservationTime),
        ]
        formData = {
          ...FORM_DATA,
          ...this.defaultData,
          startReservationTime: start,
          endReservationTime: end,
        }
        this.continueTime = end.diff(start, 'minute')
      } else {
        formData = { ...FORM_DATA }
      }
      if (this.defaultPatient) {
        formData.clinicPersonId = this.defaultPatient.id
        formData.clinicPersonName = this.defaultPatient.name
      }
      this.form = formData
      this.form.doctorId = parseInt(this.form.doctorId)
      this.form.tcId = parseInt(this.form.tcId)
      if (!this.form.doctorId) {
        this.form.doctorId = 10
      }
      if (!this.form.tcId) {
        this.form.tcId = 20
      }
      await this.getListPlan()
      await this.getListAppointment()
      this.$refs.appointmentTime.gotoDate(
        new Date(this.form.startReservationTime)
      )
      this.$refs.appointmentTime.$forceUpdate()
    },
    handleClose() {
      this.$emit('close', false)
    },
    /**
     * 获取医生列表
     */
    async getListStaff() {
      if (this.$route.path == '/market/marketView') {
        const { data } = await listStaff({
          deptId: +this.clinicId,
          postname: '医生-洁牙师',
        })
        this.doctorList = data
      } else {
        const { data } = await listStaff({
          deptId: +this.clinicId,
          postname: '医生',
        })
        this.doctorList = data
      }
    },
    /**
     * 获取休息信息
     */
    async getListPlan() {
      const { reservationDate } = this.form
      const { rows } = await listPlan({
        beginTime: reservationDate,
        endTime: reservationDate,
      })
      const map = {}
      rows.forEach((rest) => (map[rest.userId] = true))
      this.restMap = map
    },
    /**
     * 获取预约列表
     */
    async getListAppointment() {
      const { reservationDate } = this.form
      const { rows } = await listAppointment({
        beginTime: reservationDate,
        endTime: reservationDate,
      })
      this.appointmentList = rows.map((item) => ({
        ...item,
        appointmentStatus:
          item.appointmentStatus === 0 ? 1 : item.appointmentStatus,
      }))
    },
    /**
     * 设置延续时间
     */
    handleUpdateDuration(e) {
      const { startReservationTime } = this.form
      this.form.endReservationTime = startReservationTime.add(e, 'minute')
    },
    /**
     * 时间发生改变
     */
    handleDate(e) {
      const { startReservationTime, endReservationTime } = this.form
      this.$refs.appointmentTime.gotoDate(new Date(e))
      this.form.startReservationTime = dayjs(
        `${e} ${dayjs(startReservationTime).format('HH:mm')}`
      )
      this.form.endReservationTime = dayjs(
        `${e} ${dayjs(endReservationTime).format('HH:mm')}`
      )
      this.getListPlan()
      this.getListAppointment()
    },
    /**
     * 设置时间
     */
    handleEventChange(e) {
      const { start, end } = e.start ? e : e.event
      const startDate = dayjs(start)
      const endDate = dayjs(end)
      this.form.startReservationTime = startDate
      this.form.endReservationTime = endDate
      this.continueTime = dayjs(endDate).diff(startDate, 'minute')
    },
    /**
     * 设置患者 id
     */
    handleClinicPersonId(e) {
      this.form.clinicPersonId = e.id
      this.form.clinicPersonName = e.name
      this.form.personStatus = e.personStatus
      this.form.appointmentStatus = e.appointmentStatus
    },
    /**
     * 创建预约
     */
    async handleSubmit() {
      try {
        if (!this.form.clinicPersonId) {
          this.$message.warning('请选择患者')
          return
        }
        this.form.clinicPersonId = +this.form.clinicPersonId
        if (!this.form.doctorId) {
          // this.$message.warning('请选择医生')
          // return
          this.form.doctorId = 10
          this.form.doctorName = '未指定医生'
        } else {
          this.form.doctorId = +this.form.doctorId
        }
        if (this.$route.path !== '/market/marketView') {
          if (!this.form.tcId) {
            // this.$message.warning('请选择TC')
            // return
            this.form.tcId = 20
            this.form.tcName = '分诊TC'
          } else {
            this.form.tcId = +this.form.tcId
          }
        }
        this.loading = true
        const {
          startReservationTime,
          endReservationTime,
          reservationDate,
        } = this.form
        const reservationDateStr = dayjs(reservationDate).format('YYYY-MM-DD')
        const startReservationTimeStr = dayjs(startReservationTime).format(
          'HH:mm:ss'
        )
        const endReservationTimeStr = dayjs(endReservationTime).format(
          'HH:mm:ss'
        )
        const formData = {
          ...this.form,
          clinicName: this.clinicName,
          clinicId: +this.clinicId,
          createBy: this.userName,
          reservationDate: reservationDateStr,
          startReservationTime: `${reservationDateStr} ${startReservationTimeStr}`,
          endReservationTime: `${reservationDateStr} ${endReservationTimeStr}`,
        }
        if (this.types == '复诊预约') {
          formData.personStatus = '复诊'
          formData.appointmentStatus = 1
          formData.createBy = undefined
          formData.createTime = undefined
          formData.id = undefined
          formData.onClinicTime = undefined
          formData.updateBy = undefined
          formData.updateTime = undefined
          await addAppointment(formData)
          this.msgSuccess('新建复诊成功')
        } else {
          formData.id
            ? await updateAppointment(formData)
            : await addAppointment(formData)
          this.msgSuccess(formData.id ? '修改成功' : '新建成功')
        }
        this.handleClose()
        this.$emit('submit')
      } finally {
        this.loading = false
      }
    },
  },
}
</script>
